import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import axios from '../axios'
import constantRoutes from '../constant/constantRoutes'
import userApi from '../api/user.js';


Vue.use(Router)

const whiteList = ['/login', "/apply", "/applyForm",
    "/bbs", "/bbsUser/login", "/bbs/bbsindex", "/bbs/bbswrite",
]

const router = new Router({
    mode: "hash",
    routes: [...constantRoutes,]
})

//使用钩子函数判断路由是否需要拦截（钩子函数在路由前进行判断)
router.beforeEach(async (to, from, next) => {
	if (to.query.token){
		store.commit("SET_TOKEN", to.query.token);
		// 获取用户信息
		let user = JSON.parse(to.query.user);
		userApi.getUser({id:user.id}).then(res =>{
			if (res.code === 200){
				let loginUser = res.data
				store.commit("SET_USER", loginUser);
				localStorage.setItem("userInfo",JSON.stringify(loginUser));
				localStorage.setItem("role", loginUser.roleId);
			}
		}).catch(err =>{
			store.commit("SET_USER", user);
			localStorage.setItem("userInfo",to.query.user);
			localStorage.setItem("role", user.roleId);
		})
	}
    const hasToken = store.getters.token
    if (hasToken) {
        console.log("【鉴权】有token信息")
        if (to.path === '/login') {
            next({
                path: '/index'
            })
            // console.log("已登录，无需前往登录页面")
        } else {
            const hasUser = store.getters.user && store.getters.menus.length > 0
            if (hasUser) {
                console.log("【跳转】有用户信息和菜单信息")
                next()
            } else {
                try {
                    const accessRoutes = await store.dispatch('GENERATE_ROUTES')

                    router.addRoutes(accessRoutes)

                    next({
                        ...to,
                        replace: true
                    })
                } catch (error) {
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }
})

import {menu} from "../common/menu"

// 数据处理
const formatRoutes = (routes) => {

    let fmtRoutes = []
    routes.forEach(route => {
        if (route.children) {
            route.children = formatRoutes(route.children)
        }
        var str = route.component.length > 0 ? route.component : "/Home"
        // 动态加载路由
        let fmtRoute = {
            path: route.path,
            component: (resolve) => require(['../views' + str + '.vue'], resolve),
            name: route.name,
            title: route.title,
            icon: route.icon,
            hidden: route.hidden,
            children: route.children
        }
        fmtRoutes.push(fmtRoute)
    })
    return fmtRoutes
}   

// var menuRoutes = formatRoutes(menu.children)
// router.addRoutes(menuRoutes)







export default router